<template>
  <view>
    <u-modal
      v-model="show"
      :content="content"
      @confirm="confirm"
      @cancel="show = false"
      :show-cancel-button="true"
    />
    <u-search
      @search="search"
      :show-action="false"
      input-align="center"
      height="70"
      :clearabled="true"
      placeholder="请输入好友名称"
      v-model="keyword"
    />
    <u-empty v-if="isEmpty" text="您还没有添加任何好友" mode="list" />
    <view v-if="isShow">
      <view class="message-list">
        <u-swipe-action
          :show="u.show"
          :index="i"
          v-for="(u, i) in userList"
          :key="u.fid"
          @click="click"
          @open="open"
          :options="options"
        >
          <view class="uni-swipe-action" @click="toMessageDetail(u.fid)">
            <view class="item" :class="u.stick ? 'stick' : ''">
              <block>
                <view class="item-left">
                  <avatar-group :avatar="u.avatar" :text="u.name" />
                </view>
                <view class="item-middle">
                  <text class="title">{{ u.num }} {{ u.name }}</text>
                  <view class="message"><u-parse :html="u.lastMsg" /></view>
                </view>
                <view class="item-right">
                  <view class="mark" v-if="u.count > 0">{{ u.count }}</view>
                  <view class="time">{{ u.gmtCreate | dateFormat }}</view>
                </view>
              </block>
            </view>
          </view>
        </u-swipe-action>
      </view>
      <u-loadmore v-if="!isEmpty" :status="status" />
    </view>
  </view>
</template>

<script>
import avatarGroup from "@/components/avatar_group/avatar_group.vue";

export default {
  name: "user-list",
  components: {
    avatarGroup,
  },
  data() {
    return {
      isEmpty: false,
      keyword: "",
      options: [
        {
          text: "置顶",
          style: {
            backgroundColor: "#C7C6CD",
          },
        },
        {
          text: "删除",
          style: {
            backgroundColor: "#dd524d",
          },
        },
      ],
      userList: [],
      userIdAndIdxMap: new Map(),
      pageNum: 1,
      total: 0,
      pages: 0,
      status: "",
      show: false,
      content: "删除后还可从课程中添加，您确定要删除吗？",
      currentIndex: "",
      currentId: "",
      isShow: false,
    };
  },
  async onLoad() {
    uni.$emit("setVuexUserInfo", { user: null, isLoginPage: false });
    await this.initial();
    uni.$on("refreshUserChatSnapshot", this.refreshUserChatSnapshot);
    uni.$on("refreshUserChatSnapshotCount", this.refreshUserChatSnapshotCount);
    uni.$on("userListInit", this.initial);
  },
  async onPullDownRefresh() {
    this.userList = [];
    await this.initial();
    setTimeout(() => {
      uni.stopPullDownRefresh();
    }, 1000);
  },
  async onReachBottom() {
    this.pageNum = this.pageNum + 1;
    this.status = "loading";
    if (this.pageNum < this.pages) {
      await this.getChatUser();
      this.status = "loadmore";
    } else {
      this.pageNum = this.pageNum - 1;
      setTimeout(() => {
        this.status = "nomore";
      }, 1000);
    }
  },
  methods: {
    async initial() {
      // 初始化
      this.pageNum = 1;
      this.total = 0;
      this.keyword = "";
      await this.getChatUser();
    },
    async search() {
      // 搜索成功再显示
      this.isShow = false;
      this.pageNum = 1;
      await this.getChatUser();
    },
    // 查询用户
    async getChatUser() {
      const res = await this.$u.api.getChatUser({
        pageNum: this.pageNum,
        searchContent: this.keyword,
      });
      if (res.total === 0) {
        this.isEmpty = true;
      } else {
        const data = res.data;
        for (const index in data) {
          const item = data[index];
          this.userIdAndIdxMap.set(item.fid, parseInt(index));
          data[index].show = false;
          data[index].stick = false;
          if (this.$u.test.isEmpty(item.lastMsg)) {
            data[index].lastMsg = "[暂无消息]";
          }
        }
        if (this.pageNum > 1) {
          // 第二页用拼接
          this.userList.concat(data);
        } else {
          // 第一页直接赋值
          this.userList = data;
          this.isShow = true;
        }
        this.isEmpty = false;
        this.total = res.total;
      }
    },
    // 刷新用户聊天快照
    refreshUserChatSnapshot(msg) {
      const idx = this.userIdAndIdxMap.get(msg.fid);
      if (!this.$u.test.isEmpty(idx) || idx === 0) {
        const user = this.userList[idx];
        if (user.fid !== msg.fid) {
          this.refreshUserChatSnapshot(msg);
          return;
        }
        let pages = getCurrentPages();
        let page = pages.pop();
        // 如果是在聊天页面并且用户和消息ID相等时设置消息未读数为0
        if (
          page.route === "pages/pri_chat/pri_chat" &&
          page.options.fid === msg.fid
        ) {
          user.count = 0;
        } else {
          user.count++;
        }
        user.lastMsg = msg.msg;
        this.userList.splice(idx, 1);
        this.userList.unshift(user);
        if (idx !== 0) {
          this.userIdAndIdxMap.set(msg.fid, 0);
          this.userIdAndIdxMap.forEach((v, k) => {
            if (v < idx && k !== msg.fid) {
              this.userIdAndIdxMap.set(k, parseInt(v) + 1);
            }
          });
        }
      }
    },
    // 刷新用户未读消息数量为0
    refreshUserChatSnapshotCount(fid) {
      const idx = this.userIdAndIdxMap.get(fid);
      if (!this.$u.test.isEmpty(idx) || idx === 0) {
        const user = this.userList[idx];
        if (user.fid !== fid) {
          this.refreshUserChatSnapshotCount(fid);
          return;
        }
        user.count = 0;
        this.$set(this.userList, idx, user);
      }
    },
    toMessageDetail(fid) {
      this.$u.route({
        url: "pages/pri_chat/pri_chat",
        params: {
          fid: fid,
        },
      });
    },
    click(index, index1) {
      if (index1 === 1) {
        this.currentIndex = index;
        this.currentId = this.userList[index].fid;
        this.show = true;
      } else {
        // TODO 置顶
        this.$u.toast(`置顶暂未实现`);
      }
    },
    confirm() {
      this.$u.api.deleteFriend(this.currentId).then((res) => {
        if (res.code === 200) {
          this.userList.splice(this.currentIndex, 1);
          this.$u.toast("删除成功");
        }
      });
    },
    open(index) {
      this.userList[index].show = true;
      this.$set(this.userList, index, this.userList[index]);
      this.userList.map((val, idx) => {
        if (index !== idx && this.userList[idx].show) {
          this.userList[idx].show = false;
          this.$set(this.userList, idx, this.userList[idx]);
        }
      });
    },
  },
};
</script>

<style lang="scss">
.uni-swipe-action {
  width: 100%;
  overflow: hidden;
}

.item {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding: 10upx 16upx;
  background-color: #fff;
  border-bottom: 1px solid rgb(243, 243, 243);

  &.stick {
    background-color: rgba(243, 236, 221, 0.5);
  }

  .item-left {
    text-align: center;

    .image {
      width: 100rpx;
      height: 100rpx;
      border-radius: 50rpx;
      background-color: #eee;
    }

    .avatar {
      width: 100rpx;
      height: 100rpx;
      text-align: center;
      line-height: 100rpx;
      background: #4191ea;
      border-radius: 50%;
      overflow: hidden;

      .iconfont {
        width: 100rpx;
        height: 100rpx;
        text-align: center;
        line-height: 100rpx;
        color: #fff;
        font-size: 40rpx;
      }
    }
  }

  .item-middle {
    display: flex;
    flex: 1;
    flex-wrap: wrap;
    flex-direction: row;
    justify-content: flex-start;
    margin-left: 15rpx;
    overflow: hidden;

    .title {
      width: 100%;
      color: #000;
      font-family: "微软雅黑";
      font-weight: 400;
      font-size: 37rpx;
      height: 50rpx;
      line-height: 60rpx;
      overflow: hidden;
      /*自动隐藏文字*/
      text-overflow: ellipsis;
      /*文字隐藏后添加省略号*/
      white-space: nowrap;
      /**强制不换行*/
    }

    .message {
      width: 100%;
      font-family: "微软雅黑";
      color: #808080;
      height: 50rpx;
      font-weight: bold;
      line-height: 40rpx;
      font-size: 27rpx;
      overflow: hidden;
      /**自动隐藏文字*/
      text-overflow: ellipsis;
      /**文字隐藏后添加省略号*/
      white-space: nowrap;
      /**强制不换行*/
    }
  }

  .item-right {
    overflow: hidden;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 27rpx;
    font-weight: bold;

    .time {
      color: #808080;
      height: 60rpx;
      line-height: 60rpx;
    }

    .mark {
      background-color: #f74c31;
      line-height: 35rpx;
      text-align: center;
      font-size: 20rpx;
      min-width: 35rpx;
      min-height: 35rpx;
      border-radius: 18rpx;
      color: #fff;
    }
  }
}
</style>
